

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SERVER {

    // Declaration section:
    // declare a server socket and a client socket for the server
    // declare an input and an output stream
    static Socket clientSocket = null;
    static ServerSocket serverSocket = null;
    // This chat server can accept up to 10 clients' connections
    static clientThread t[] = new clientThread[10];

    public static void main(String args[]) {
// The default port

        int port_number = 2222;
        if (args.length < 1) {
            System.out.println("Usage: java MultiThreadChatServer \n"
                    + "Now using port number=" + port_number);
        } else {
            port_number = Integer.valueOf(args[0]).intValue();
        }
// Initialization section:
// Try to open a server socket on port port_number (default 2222)
// Note that we can't choose a port less than 1023 if we are not
// privileged users (root)

        try {
            serverSocket = new ServerSocket(port_number);
        } catch (IOException e) {
            System.out.println(e);
        }
// Create a socket object from the ServerSocket to listen and accept 
// connections.
// Open input and output streams for this socket will be created in 
// client's thread since every client is served by the server in
// an individual thread
        while (true) {
            try {
                clientSocket = serverSocket.accept();
                for (int i = 0; i <= 9; i++) {
                    if (t[i] == null) {
                        (t[i] = new clientThread(clientSocket, t)).start();
                        break;
                    }
                }
            } catch (IOException e) {
                System.out.println(e);
            }
        }
    }
}

// This client thread opens the input and the output streams for a particular client,
// ask the client's name, informs all the clients currently connected to the 
// server about the fact that a new client has joined the chat room, 
// and as long as it receive data, echos that data back to all other clients.
// When the client leaves the chat room this thread informs also all the
// clients about that and terminates. 
class clientThread extends Thread {

    int intentos = 3;
    String ruta = "\\";
    DataInputStream is = null;
    PrintStream os = null;
    Socket clientSocket = null;
    clientThread t[];

    public clientThread(Socket clientSocket, clientThread[] t) {
        this.clientSocket = clientSocket;
        this.t = t;
    }

    @Override
    public void run() {
        try {
            BufferedReader bf = null;
            try {
                bf = new BufferedReader(new FileReader("C:\\log.txt"));
            } catch (FileNotFoundException ex) {
                Logger.getLogger(clientThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            os = new PrintStream(clientSocket.getOutputStream());
            is = new DataInputStream(clientSocket.getInputStream());
            BufferedReader bR = new BufferedReader(new InputStreamReader(System.in));
            try {
                String[] comandoInicial;
                String aux;
                HashMap<String, String> userPass = new HashMap();
                int intentos = 3;
                while ((aux = bf.readLine()) != null) {
                    String[] uP = aux.split(" ");
                    userPass.put(uP[0], uP[1]);
                }

                while (true) {
                    comandoInicial = is.readLine().split(" ");
                    if (comandoInicial[0].equals("log")) {
                        os.println("Contrasena: ");
                        String contra = is.readLine();
                        if (userPass.get(comandoInicial[1]) != null
                                && userPass.get(comandoInicial[1]).equals(contra)) {
                            os.println("Acceso permitido");
                            break;
                        } else if (--intentos <= 0) {
                            os.println("Adios");
                            clientSocket.close();
                        } else {
                            os.println("Usuario o contrasena incorrectos");
                        }
                    }
                }
                while (true) {
                    String texto = ruta + "> ";
                    os.print(texto.toCharArray());
                    String[] ordenCompleta;
                    ordenCompleta = is.readLine().split(" ");

                    if (ordenCompleta[0].equals("dirR")) {
                        try {
                            File directorio = new File(ruta);
                            File[] archivos = directorio.listFiles();
                            for (int i = 0; i < archivos.length; i++) {
                                os.println(archivos[i].toString());
                            }
                        } catch (Exception ex) {
                            os.println("La ruta especificada no existe");
                        }
                    } else if (ordenCompleta[0].equals("IP")) {
                        test();
                    } else if (ordenCompleta[0].equals("rmR")) {
                        try {
                            File Aborrar = new File("c:\\" + ruta + "\\" + ordenCompleta[1]);
                            boolean success = Aborrar.delete();
                            if (!success) {
                                os.println("No se puede borrar");
                            }
                            if (success) {
                                os.println("Archivo borrado");
                            }
                        } catch (Exception ex) {
                            os.println("La ruta especificada no existe");
                        }
                    } else if (ordenCompleta[0].equals("cd")) {
                        if (ordenCompleta.length > 1) {
                            if (ordenCompleta[1].equals("..")) {
                                if (!ruta.equals("")) {
                                    ruta = ruta.substring(0, ruta.lastIndexOf("\\"));
                                    if (ruta.equals("")) {
                                        ruta = "\\";
                                    }
                                }
                            } else {
                                if (new File(ruta + ordenCompleta[1]).isDirectory()) {
                                    ruta += ordenCompleta[1];
                                } else if (new File(ruta + "\\" + ordenCompleta[1]).isDirectory()) {
                                    ruta += "\\" + ordenCompleta[1];
                                } else {
                                    os.println("La ruta especificada no existe");
                                }
                            }
                        }
                    } else if (ordenCompleta[0].equals("cpR")) {
                        if (ordenCompleta.length == 3) {
                            File archivoACopiar;
                            OutputStream out;
                            //Buscamos en el camino que fue proporcionado
                            if (new File(ordenCompleta[2]).isDirectory()) {
                                if (new File(ordenCompleta[1]).isFile()) {
                                    archivoACopiar = new File(ordenCompleta[1]);
                                    try (InputStream in = new FileInputStream(archivoACopiar)) {
                                        try {
                                            out = new FileOutputStream(ordenCompleta[2] + "/" + archivoACopiar.getName());
                                            byte[] buf = new byte[1024];
                                            int len;
                                            while ((len = in.read(buf)) > 0) {
                                                out.write(buf, 0, len);
                                            }
                                            in.close();
                                            out.close();
                                        } catch (Exception ex) {
                                            os.println(ex.getMessage());
                                        }
                                    } catch (Exception ex) {
                                        os.println(ex.getMessage());
                                    }
                                } //Buscamos en root
                                else if (new File(ruta + ordenCompleta[1]).isFile()) {
                                    archivoACopiar = new File("\\" + ordenCompleta[1]);
                                    try (InputStream in = new FileInputStream(archivoACopiar)) {
                                        try {
                                            out = new FileOutputStream(ordenCompleta[2] + "/" + archivoACopiar.getName());
                                            byte[] buf = new byte[1024];
                                            int len;
                                            while ((len = in.read(buf)) > 0) {
                                                out.write(buf, 0, len);
                                            }
                                            in.close();
                                            out.close();
                                        } catch (Exception ex) {
                                            os.println(ex.getMessage());
                                        }
                                    }
                                } //Buscamos en el directorio en el que estamos
                                else if (new File(ruta + "\\" + ordenCompleta[1]).isFile()) {
                                    archivoACopiar = new File(ruta + "\\" + ordenCompleta[1]);
                                    try (InputStream in = new FileInputStream(archivoACopiar)) {
                                        try {
                                            out = new FileOutputStream(ordenCompleta[2] + "/" + archivoACopiar.getName());
                                            byte[] buf = new byte[1024];
                                            int len;
                                            while ((len = in.read(buf)) > 0) {
                                                out.write(buf, 0, len);
                                            }
                                            in.close();
                                            out.close();
                                        } catch (Exception ex) {
                                            os.println(ex.getMessage());
                                        }
                                    }
                                } else {
                                    os.println("El archivo no existe o escribio la ruta de manera incorrecta");
                                }
                            } else {
                                os.println("El directorio destino no existe o escribio la ruta de manera incorrecta");
                            }
                        } else {
                            os.println("Comando incorrecto");
                        }
                    } else if (ordenCompleta[0].equals("Kbye")) {
                        os.println("Adios");
                        clientSocket.close();
                    }
                }
            } catch (IOException e) {
            }
        } catch (IOException ex) {
            Logger.getLogger(clientThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void test() {
        try {
            InetAddress localhost = InetAddress.getLocalHost();
            InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
            if (allMyIps != null && allMyIps.length >= 1) {
                for (int i = 0; i < allMyIps.length; i++) {
                    System.out.println(" " + allMyIps[i]);
                }
            }
        } catch (UnknownHostException e) {
            System.out.println("(error retrieving server host name)");
        }
    }
}